package com.android.jay.lib_network.okhttp_learn;

import java.io.File;
import java.util.Map;

import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.Request;
import okhttp3.RequestBody;

/**
 * Created by wzp on 2020/3/1 0001.
 * <p>
 * 描述  ：创建各式各样的请求
 */
public class CommonRequest {

    /**
     * 创建一个get请求
     **/

    public static Request createGetRequest(String url, RequestParams requestParams) {
        StringBuilder stringBuilder = new StringBuilder(url).append("?");
        if (requestParams != null) {
            for (Map.Entry<String, String> entry : requestParams.urlParams.entrySet()) {
                stringBuilder.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
            }
        }
        return new Request.Builder().url(stringBuilder.substring(0, stringBuilder.length() - 1)).get().build();
    }

    public static Request creataPostRequest(String url, RequestParams requestParams) {
        FormBody.Builder formBody = new FormBody.Builder();
        if (requestParams != null) {
            for (Map.Entry<String, String> entry : requestParams.urlParams.entrySet()) {
                formBody.add(entry.getKey(), entry.getValue());
            }
        }
        FormBody body = formBody.build();
        return new Request.Builder().url(url).post(body).build();
    }

    /**
     * 文件上传
     **/

    private static final MediaType FILE_TYPE = MediaType.parse("application/octet-stream");

    public static Request createMultiPostRequest(String url, RequestParams params) {

        MultipartBody.Builder builder = new MultipartBody.Builder();
        builder.setType(MultipartBody.FORM);
        if (params != null) {
            for (Map.Entry<String, Object> entry : params.fileParams.entrySet()) {
                if (entry.getValue() instanceof File) {
                    builder.addPart(MultipartBody.Part.createFormData(entry.getKey(), null,
                            RequestBody.create(FILE_TYPE, (File) entry.getValue())));
                } else {
                    builder.addFormDataPart(entry.getKey(), String.valueOf(entry.getValue()));
                }


            }
        }

        MultipartBody body = builder.build();
        return new Request.Builder().url(url).post(body).build();

    }


}
